package com.sinosoft.web.easyui.api;

import cn.com.sinux.spring.commons.PropertyCollection;
import cn.com.sinux.spring.json.JsonFilter;
import cn.com.sinux.spring.utils.PageUtils;
import com.sinosoft.hydra.um.LoginUser;
import com.sinosoft.hydra.um.condition.SearchDocumentCondition;
import com.sinosoft.hydra.um.condition.SearchDocumentCopyCondition;
import com.sinosoft.hydra.um.constant.BaseConstant;
import com.sinosoft.hydra.um.domain.permission.*;
import com.sinosoft.hydra.um.helper.LoggerHelper;
import com.sinosoft.hydra.um.services.DocumentService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collections;
import java.util.List;

/**
 * 文档管理API
 */
@Controller
@RequestMapping("api/document")
public class SysDocumentApi {

    @Autowired
    private DocumentService documentService;

    /**
     * 添加文档
     *
     * @param tDocument 文档
     * @param loginUser 登录用户
     * @return 保存结果
     * @throws Exception
     */
    @RequestMapping(value = "addDocumentForJson", method = RequestMethod.POST)
    @RequiresPermissions(value = "document:data:add")
    @ResponseBody
    public Object addDocumentForJson(TDocument tDocument, LoginUser loginUser) throws Exception {
        TDocument document = documentService.addDocument(loginUser, tDocument);
        LoggerHelper.logInfo("添加了文档{}", tDocument.getAttachmentName());
        return JsonFilter.doPropertyFilter(document, new PropertyCollection()
                .addProperties("id", "docName"));
    }

    /**
     * 修改文档
     *
     * @param tDocument 文档
     * @param loginUser 登录用户
     * @return 保存结果
     * @throws Exception
     */
    @RequestMapping(value = "updateDocumentForJson", method = RequestMethod.POST)
    @RequiresPermissions(value = "document:data:update")
    @ResponseBody
    public Object updateDocumentForJson(TDocument tDocument, LoginUser loginUser,
                                        @RequestParam(value = "copyId", required = true) String copyId) throws Exception {
        TDocument doc = documentService.modifyDocument(copyId, tDocument, loginUser);
        LoggerHelper.logInfo("修改了文档‘{}’", tDocument.getAttachmentName());
        return JsonFilter.doPropertyFilter(doc, new PropertyCollection()
                .addProperties("id", "docName"));
    }

    /**
     * ajax删除资源
     *
     * @param searchDocumentCondition 搜索条件
     * @return true
     */
    @RequestMapping(value = "deleteDocuments", method = RequestMethod.POST)
    @RequiresPermissions(value = "document:data:delete")
    @ResponseBody
    public Object delDocumentForJson(SearchDocumentCondition searchDocumentCondition) throws Exception {
        List<TDocument> documents = documentService.delDocuments(searchDocumentCondition.getIds());
        LoggerHelper.logInfo("删除了文档‘{}’", new LoggerHelper.PropertyReader<TDocument>(documents, "docName"));
        return JsonFilter.doPropertyFilter(documents, new PropertyCollection()
                .addProperties("id", "docName"));
    }

    /**
     * 搜索所有文档
     *
     * @param searchDocumentCondition 搜索条件
     * @param pageNumber 分页数
     * @param pageSize 单页条数
     * @return 分页对象
     * @throws Exception
     */
    @RequestMapping(value = "allList")
    @ResponseBody
    public Object allList(SearchDocumentCondition searchDocumentCondition, @RequestParam(value = "page", required = false, defaultValue = "0") Integer pageNumber,
                          @RequestParam(value = "rows", required = false, defaultValue = "10") Integer pageSize) throws Exception {
        Pageable pageable = PageUtils.buildPageRequest(pageNumber, pageSize, "docNow.createTime", "desc");
        Page<TDocumentCopy> page = documentService.findDocuments(searchDocumentCondition,pageable);
        return JsonFilter.doPropertyFilter(page, new PropertyCollection()
                .addProperties(TDocumentCopy.class, "id", "docNow", "docRangeType")
                .addProperties(TDocument.class, "docName", "moduleType", "docKeyWord", "createUser", "createTime", "docBelong", "docStatus", "version")
                .addProperties(TDirectory.class, "dirValue")
                .addProperties(SysOrganization.class, "orgName")
                .addProperties(SysUserMember.class, "userName"));
    }

    /**
     * 获取我的文档
     *
     * @param loginUser 当前登录用户
     * @param searchDocumentCondition 搜索条件
     * @param pageNumber 分页数
     * @param pageSize 单页条数
     * @return 分页对象
     * @throws Exception
     */
    @RequestMapping(value = "myList")
    @ResponseBody
    public Object myList(LoginUser loginUser, SearchDocumentCondition searchDocumentCondition, @RequestParam(value = "page", required = false, defaultValue = "0") Integer pageNumber,
                          @RequestParam(value = "rows", required = false, defaultValue = "10") Integer pageSize) throws Exception {
        Pageable pageable = PageUtils.buildPageRequest(pageNumber, pageSize, "docNow.createTime", "desc");
        Page<TDocumentCopy> page = documentService.findMyDocuments(searchDocumentCondition,loginUser,pageable);
        return JsonFilter.doPropertyFilter(page, new PropertyCollection()
                .addProperties(TDocumentCopy.class, "id", "docNow", "docRangeType")
                .addProperties(TDocument.class, "docName", "moduleType", "docKeyWord", "createUser", "createTime", "docBelong", "docStatus", "version")
                .addProperties(TDirectory.class, "dirValue")
                .addProperties(SysOrganization.class, "orgName")
                .addProperties(SysUserMember.class, "userName"));
    }

    /**
     * 设置访问权限
     *
     * @param condition 保存条件
     * @return true
     */
    @RequestMapping(value = "saveRange")
    @ResponseBody
    public Object saveRange(SearchDocumentCopyCondition condition) throws Exception {
        TDocument document = documentService.saveRange(condition.getId(), condition.getDocRangeType(), condition.getUserIds());
        LoggerHelper.logInfo("修改了文档的访问范围‘{}’", document.getAttachmentName());
        return JsonFilter.doPropertyFilter(document, new PropertyCollection()
                .addProperties("id", "docName"));
    }

    /**
     * 发布文档
     *
     * @param id 发布文档的编号
     * @return 发布结果
     */
    @RequestMapping(value = "publish")
    @ResponseBody
    public Object publish(@RequestParam(value = "id", required = true) String id) {
        TDocumentCopy copy = documentService.findOne(id);
        List<TDocument> documents = documentService.publishDocuments(Collections.singletonList(copy.getDocNow().getId()), BaseConstant.DocStatus.DOC_STATUS_PUBLISHED);
        LoggerHelper.logInfo("发布了文档‘{}’", new LoggerHelper.PropertyReader<TDocument>(documents, "docName"));
        return JsonFilter.doPropertyFilter(documents, new PropertyCollection()
                .addProperties("id", "docName"));
    }

    /**
     * 到新增文档页面
     *
     * @return 页面
     */
    @RequestMapping("toAdd")
    @RequiresPermissions(value = "document:data:add")
    public String toAdd() {
        return "hydra_easyui/document/addDocument";
    }

    /**
     * 到修改文档页面
     *
     * @param model 对象
     * @param id 编号
     * @return 页面
     */
    @RequestMapping("toUpdate")
    @RequiresPermissions(value = "document:data:update")
    public String toUpdate(Model model,
                           @RequestParam(value = "id", required = true) String id) {
        model.addAttribute("documentCopy", documentService.findOne(id));
        return "hydra_easyui/document/modifyDocument";
    }

    /**
     * 到设置访问权限页面
     *
     * @param model 模型对象
     * @param id 编号
     * @return 页面
     */
    @RequestMapping("toRange")
    @RequiresPermissions(value = "document:data:range")
    public String toRange(Model model,
                          @RequestParam(value = "id", required = true) String id,
                          @RequestParam(value = "publish", required = true) Boolean publish) {
        model.addAttribute("documentCopy", documentService.findOne(id));
        model.addAttribute("publish", publish);
        return "hydra_easyui/document/setRange";
    }


    /**
     * 文库管理首页
     *
     * @return String 页面名称
     */
    @RequestMapping("index")
    @RequiresPermissions(value = "document:data:list")
    public String listView() {
        LoggerHelper.logInfo("访问了文档资源列表‘{}’");
        return "hydra_easyui/document/index";
    }

    /**
     * 文档搜索页面
     *
     * @return String 页面名称
     */
    @RequestMapping("search")
    @RequiresPermissions(value = "document:data:list")
    public String search() {
        return "hydra_easyui/document/search";
    }

    /**
     * 文档下载
     *
     * @return String 页面名称
     */
    @RequestMapping("download")
    @RequiresPermissions(value = "document:data:download")
    public String download(@RequestParam(value = "id", required = true) String id) throws Exception {
        TDocument tDocument = documentService.changeDownloadTimes(id);
        LoggerHelper.logInfo("下载了文档资源‘{}’", tDocument.getAttachmentName());
        return "redirect:/download" + tDocument.getAttachment() + "?f=" + new String(tDocument.getAttachmentName().getBytes("UTF-8"), "ISO8859-1");
    }

    /**
     * 文档详情
     *
     * @param model 模型
     * @param id 编号
     * @return 页面
     */
    @RequestMapping(value = "detail")
    public String detail(Model model, @RequestParam(value = "id", required = true) String id) {
        model.addAttribute("copy", documentService.findCopyByDoc(id));
        model.addAttribute("document", documentService.findDetail(id));
        model.addAttribute("type", documentService.findDetailType(id));
        List<TDocument> documents = documentService.versionList(id);
        model.addAttribute("versions", documents);
        model.addAttribute("versionTotal", documents.size());
        return "hydra_easyui/document/detail";
    }

    /**
     * 获取我的文档页面
     *
     * @param model 模型
     * @param loginUser  用户
     * @return 页面
     */
    @RequestMapping(value = "myDocument")
    public String myDocument(Model model, LoginUser loginUser) {
        LoggerHelper.logInfo("访问了个人的文档列表");
        model.addAttribute("loginUser",loginUser);
        return "hydra_easyui/document/myDocument";
    }
}
